<?php

namespace app\models;

use Yii;
use yii\base\Exception;
use yii\base\Model;

/**
 * 卡设置套餐表单
 * Class CardSetPackageForm
 * @package app\models
 */
class CardSetPackageForm extends Model
{
    /**
     * @var string 卡来源 iccid range search
     */
    public $source;
    /**
     * @var string 多条ICCID
     */
    public $iccid_list;
    /**
     * @var string ICCID开始号码
     */
    public $iccid_start;
    /**
     * @var string ICCID结束号码
     */
    public $iccid_end;
    /**
     * @var integer 搜索接口编号
     */
    public $search_api_id;
    /**
     * @var integer 搜索运营商编号
     */
    public $search_isp_id;
    /**
     * @var string 搜索批次号
     */
    public $search_batch_no;
    /**
     * @var integer 套餐编号
     */
    public $package_id;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['source', 'default', 'value' => 'iccid'],
            [['iccid_list', 'iccid_start', 'iccid_end'], 'safe'],
            [['search_api_id', 'search_isp_id'], 'integer'],
            [['source', 'package_id'], 'required'],
            ['package_id', 'integer'],
            ['search_batch_no', 'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'source' => '来源',
            'iccid_list' => 'ICCID列表',
            'iccid_start' => 'ICCID开始号码',
            'iccid_end' => 'ICCID结束号码',
            'search_api_id' => '搜索接口',
            'search_isp_id' => '搜索运营商',
            'search_batch_no' => '搜索批次号',
            'package_id' => '套餐',
        ];
    }

    /**
     * 设置套餐
     * @return boolean
     */
    public function setPackage()
    {
        if (!$this->validate()) {
            return false;
        }
        /** @var Card[] $cardList */
        $cardList = [];
        if ($this->source == 'iccid') {
            // 直接填写
            $iccidList = preg_split('/\s/', $this->iccid_list, -1, PREG_SPLIT_NO_EMPTY);
            if (empty($iccidList)) {
                $this->addError('iccid_list', '没有找到任何待分配的卡。');
                return false;
            }
            foreach ($iccidList as $iccid) {
                $card = Card::findOne(['iccid' => $iccid]);
                if (empty($card)) {
                    $this->addError('iccid_list', 'ICCID【' . $iccid . '】不是有效的卡。');
                    return false;
                }
                if (!empty($card->package_id) && !empty($card->uid)) {
                    $this->addError('iccid_list', 'ICCID【' . $card->iccid . '】已经有套餐且分配给用户了。');
                    return false;
                }
                $cardList[] = $card;
            }
        } elseif ($this->source == 'range') {
            // 起止卡号
            if (empty($this->iccid_start)) {
                $this->addError('iccid_start', 'ICCID开始号码必须填写。');
                return false;
            }
            if (empty($this->iccid_end)) {
                $this->addError('iccid_end', 'ICCID结束号码必须填写。');
                return false;
            }
            if (strlen($this->iccid_start) != strlen($this->iccid_end)) {
                $this->addError('iccid_end', 'ICCID开始号码和结束号码长度不一致。');
                return false;
            }
            // 范围内的ICCID列表
            for ($i = 0; $i < strlen($this->iccid_start); $i++) {
                if ($this->iccid_start[$i] != $this->iccid_end[$i]) {
                    $prefix = substr($this->iccid_start, 0, $i);
                    $iccidList = range(substr($this->iccid_start, $i), substr($this->iccid_end, $i));
                    $chrLen = strlen(substr($this->iccid_start, $i));
                    foreach ($iccidList as $item) {
                        $iccid = $prefix . str_pad($item, $chrLen, '0', STR_PAD_LEFT);
                        $cardList[] = Card::findOne(['iccid' => $iccid]);
                    }
                    break;
                }
            }
        } elseif ($this->source == 'search') {
            // 通过查询条件搜索
            $query = Card::find();
            $query->andFilterWhere(['api_id' => $this->search_api_id]);
            $query->andFilterWhere(['isp_id' => $this->search_isp_id]);
            $query->andFilterWhere(['batch_no' => $this->search_batch_no]);
            /** @var Card $card */
            foreach ($query->each() as $card) {
                if (!empty($card->package_id) && !empty($card->uid)) {
                    $this->addError('iccid_list', 'ICCID【' . $card->iccid . '】已经有套餐且分配给用户了。');
                    return false;
                }
                $cardList[] = $card;
            }
        }
        $package = Package::findOne(['id' => $this->package_id]);
        if (empty($package)) {
            $this->addError('package_id', '没有找到套餐信息。');
            return false;
        }

        $trans = Yii::$app->db->beginTransaction();
        try {
            foreach ($cardList as $card) {
                $card->package_id = $package->id;
                $card->save(false);
            }
            $trans->commit();
            return true;
        } catch (Exception $e) {
            try {
                $trans->rollBack();
            } catch (Exception $_) {
            }
        }
        return false;
    }
}
